/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation;
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <iostream>
#include <fstream>

#include "ns3/core-module.h"
#include "ns3/csma-module.h"
#include "ns3/internet-module.h"

#include "ns3/wifi-module.h"
#include "ns3/mobility-module.h"
#include "ns3/stats-module.h"
#include "ns3/tap-bridge-helper.h"
using namespace ns3;

NS_LOG_COMPONENT_DEFINE ("TapManet");


void printTime(int interval) {
	
	Ptr<RealtimeSimulatorImpl> impl = DynamicCast<RealtimeSimulatorImpl>(Simulator::GetImplementation ()); 
	Time real_time = impl->RealtimeNow();

	Time sim_time = Simulator::Now();

	std::cout << "drift:" << real_time.GetMilliSeconds() << ":" << sim_time.GetMilliSeconds() << ":" << (real_time.GetMilliSeconds() - sim_time.GetMilliSeconds()) << std::endl;
	Simulator::Schedule(Seconds(interval), &printTime, interval);
}

int 
main (int argc, char *argv[])
{
  CommandLine cmd;
  
  uint32_t maxNodes=2, nodeSpacing = 100, duration = 900, seed = 1, gridWidth=4, mtu=2304;
  string runID;
  string input;
  string mobile;
  
  cmd.AddValue ("node_spacing", "Spacing between neighbouring nodes", nodeSpacing);  
  cmd.AddValue ("duration", "Duration of simulation", duration);  
  cmd.AddValue ("seed", "Random seed for simulation", seed);
  cmd.AddValue ("nodes", "Nodes used in simulation", maxNodes);  
  cmd.AddValue ("nodes_per_row", "Nodes per row in grid", gridWidth);
  cmd.AddValue ("runID", "Identifier of this run", runID);
  cmd.AddValue ("input", "experiment name (currently not used)", input);
  cmd.AddValue ("speed", "Move nodes with random waypoint, 2:4 m/s uniform", mobile);
  cmd.AddValue ("mtu", "MTU to use.", mtu);
  
  cmd.Parse (argc,argv);

  string format("omnet");
  
  string experiment("manet");
    
  std::stringstream tmp;
  tmp << "static-seed" << seed << "-nodes" << maxNodes << "-runID" << runID << "-duration" << duration << "-input" << input << "-spacing" << nodeSpacing;
  cout << tmp.str() << endl;    
  string strategy(tmp.str());  

  SeedManager::SetSeed (seed);
  GlobalValue::Bind ("SimulatorImplementationType", StringValue ("ns3::RealtimeSimulatorImpl"));
  GlobalValue::Bind ("ChecksumEnabled", BooleanValue (true));  

  NodeContainer nodes;
  nodes.Create (maxNodes);

  WifiHelper wifi = WifiHelper::Default ();
  wifi.SetStandard (WIFI_PHY_STANDARD_80211a);
  wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager", "DataMode", StringValue ("OfdmRate6Mbps"));
  NqosWifiMacHelper wifiMac = NqosWifiMacHelper::Default ();
  wifiMac.SetType ("ns3::AdhocWifiMac");

  YansWifiChannelHelper wifiChannel = YansWifiChannelHelper::Default ();
  YansWifiPhyHelper wifiPhy = YansWifiPhyHelper::Default ();
  wifiPhy.SetChannel (wifiChannel.Create ());

  NetDeviceContainer devices = wifi.Install (wifiPhy, wifiMac, nodes);
  
  MobilityHelper mobility;

  mobility.SetPositionAllocator ("ns3::GridPositionAllocator",
      "MinX", DoubleValue (nodeSpacing/2),
      "MinY", DoubleValue (nodeSpacing/2),
      "DeltaX", DoubleValue (nodeSpacing),
      "DeltaY", DoubleValue (nodeSpacing),
      "GridWidth", UintegerValue (gridWidth),
      "LayoutType", StringValue ("RowFirst"));

   cout << "grid starts at " << nodeSpacing << "," << nodeSpacing << ", width is " << gridWidth << ", nodespacing is " << nodeSpacing << endl;
      
  StringValue speed = StringValue(mobile);
  StringValue nomobility = StringValue("0");
  if (nomobility.Get().compare(0,speed.Get().length(),speed.Get()) != 0) { 
    mobility.SetMobilityModel ("ns3::RandomWalk2dMobilityModel",
          "Bounds", RectangleValue (Rectangle (0, nodeSpacing*gridWidth+nodeSpacing, 0, nodeSpacing*gridWidth+nodeSpacing)),
          "Distance", DoubleValue(100),
          "Speed", speed); 
    cout << "speed is " << speed.Get() << endl;   
    cout << "random walk bounds are x: 0 to " << nodeSpacing*gridWidth+nodeSpacing << ", y: 0 to " << nodeSpacing*gridWidth+nodeSpacing << endl; 
  } else {      
    mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");  
    cout << "no mobility" << endl;
  }
  mobility.Install(nodes);

  TapBridgeHelper tapBridge;
  tapBridge.SetAttribute ("Mode", StringValue ("UseLocal"));
  tapBridge.SetAttribute ("Mtu", UintegerValue(mtu));

  for (uint32_t i = 1; i <= maxNodes; i++) {
    std::stringstream ss;
    ss << "tap-" << i;
    cout << "adding device " << ss.str() << "\n";
    tapBridge.SetAttribute ("DeviceName", StringValue (ss.str()));
    tapBridge.Install (nodes.Get (i-1), devices.Get (i-1));
  }
  
  
  cout << "Starting simulation. Will run for " << duration << " seconds...\n";  
  Simulator::Schedule(Seconds(0), &printTime, 1);
  Simulator::Stop (Seconds (duration));

  Simulator::Run();

  Simulator::Destroy ();
  
  cout << "Done.\n";
}
